package baomidou.service.impl;

import baomidou.service.BaseService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import baomidou.service.model.BaseEntity;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author zhanglinfeng
 * @date create in 2023/3/6 11:48
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> implements BaseService<T> {

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public Optional<T> unique(Serializable id) {
        T entity = this.getById(id);
        return Optional.ofNullable(entity);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public Optional<T> unique(@NotNull LambdaQueryWrapper<T> query) {
        query.last(" limit 1");
        T entity = this.getOne(query);
        return Optional.ofNullable(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(@NotNull T entity) {
        entity.setUpdateTime(LocalDateTime.now());
        return this.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(@NotNull T entity) {
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        return this.save(entity);
    }

}
